<?php

class ProjectPresenter extends BasePresenter
{

	/**
	 * @persistent
	 */
	public $orderBy = 'deadline';
	/**
	 * @persistent
	 */
	public $direction = 'asc';
	private $id = null;
	private $milestone = null;

	public function renderDefault()
	{
		$projects = $this->context->models->projects;
		if ($this->getUser()->isAllowed('project', 'show'))
		{
			$this->template->projects = $projects->getPublicProjects($this->user->id);
		} else
		{
			$this->template->projects = $projects->getUserProjects($this->user->id);
		}
	}

	public function renderOverview($id)
	{
		$this->checkUser($id);
		$this->id = $id;
		$project = $this->context->models->project->find($this->id);
		$this->template->project = $project->getProject();
		$this->template->children = $project->getChildren();
		$this->template->team = $project->getProjectTeam();
		$tasks = $project->getTasks();

		if ($this->direction != 'asc' && $this->direction != 'desc')
			$this->direction = 'asc';

		$tasks->order("IF(task_status.completed='no',0,1)");

		switch ($this->orderBy)
		{
			case 'priority':
				$tasks->order('task_priority.priority ' . $this->direction);
				break;
			case 'name':
				$tasks->order('name ' . $this->direction);
				break;
			case 'project':
				$tasks->order('project.name ' . $this->direction);
				break;
			case 'worker':
				$tasks->order('worker.surname ' . $this->direction . ', worker.name ' . $this->direction);
				break;
			case 'deadline':
				if ($this->direction == 'asc')
					$tasks->order('IF(ISNULL(task.deadline),1,0),task.deadline asc');
				else
					$tasks->order('IF(ISNULL(task.deadline),0,1),task.deadline desc');
				break;
			case 'completed':
				$tasks->order('completed ' . $this->direction);
				break;
		}

		$this->template->tasks = $tasks;

		$priority = $this->context->models->taskContext;
		$this->template->priorities = $priority->getPriorities();
	}

	public function renderMilestones($id)
	{
		$this->checkUser($id);
		$this->id = $id;
		$project = $this->context->models->project->find($this->id);
		$this->template->project = $project->getProject();
		$this->template->children = $project->getChildren();
		$this->template->team = $project->getProjectTeam();
		$milestones = $project->getMilestones();
		$this->template->milestones = $milestones;

		//$ids = array_keys($milestones->fetchPairs('id', 'name'));
		//$tasks = $project->getTasksInMilestones($ids);
		//$this->template->tasks = $tasks;
	}

	public function renderFlowChart($id)
	{
		$this->checkUser($id);
		$this->id = $id;
		$project = $this->context->models->project->find($this->id);
		$this->template->project = $project->getProject();
		$this->template->tasks = $project->getTasks();

		$this->template->prerequisites = $project->getPrerequisites();
	}

	public function renderDocuments($id)
	{
		$this->checkUser($id);
		$this->id = $id;
		$project = $this->context->models->project->find($this->id);
		$this->template->project = $project->getProject();
		$this->template->children = $project->getChildren();
		$this->template->team = $project->getProjectTeam();

		$files = $project->getFiles();
		$this->template->types = $files;
	}

	public function renderCalendar($id)
	{
		$this->checkUser($id);
		$this->id = $id;
		$calendarModel = $this->context->models->calendar;
		$project = $this->context->models->project->find($id)->getProject();
		$this->template->weeks = $calendarModel->getProjectCalendar($project);
	}

	protected function afterRender()
	{
		parent::afterRender();
		if ($this->id != null)
		{
			$this->template->id = $this->id;
			$this->template->projectResource = new \Tasker\Authorization\ProjectResource($this->id);
		}
	}

	public function handleOrderBy($by)
	{

		$allowOrderBy = array('priority', 'name', 'worker', 'deadline', 'completed');

		if (in_array($by, $allowOrderBy))
		{
			if ($this->orderBy == $by && $this->direction == 'asc')
				$this->direction = 'desc';
			else
				$this->direction = 'asc';

			$this->orderBy = $by;
		}

		if (!$this->isAjax())
		{
			$this->redirect('this');
		} else
		{
			$this->invalidateControl("tasks");
		}
	}

	public function renderSettings($id)
	{
		$this->template->projectID = $id;
	}

	protected function createComponentProjectForm()
	{
		return new \Tasker\Components\Forms\ProjectForm();
	}

	protected function createComponentEditProject($name)
	{

		$form = $this->generateProjectForm($name);
		$form->onSuccess[] = callback($this, '');

		return $form;
	}

	public function handleFilterUsersBySkill()
	{
		if ($this->isAjax())
		{
			
		} else
		{
			throw new \Nette\Application\BadRequestException("AJAX expected");
		}
	}

	public function renderAddProject($parent = null)
	{
		$this->addComponent(new \Tasker\Components\Forms\ProjectForm($parent), 'projectForm');
	}

	public function renderAddTask($id)
	{
		$this->template->project = $id;
	}

	public function renderEditTask($id)
	{
		$this->template->id = $id;
	}

	protected function createComponentTaskForm($name)
	{
		return new Tasker\Components\Forms\TaskForm();
	}

	protected function checkUser($projectId)
	{
		if (!$this->getUser()->isAllowed('project', 'show'))
		{
			$isUserInProject = $this->context->models->projects->getUserProjects($this->user->id, array('id' => $projectId))->fetch();
			if ($isUserInProject === false)
			{
				$this->redirect('default');
			}
		}
	}

	public function renderAddMilestone($id)
	{
		$this->id = $id;
	}

	public function renderEditMilestone($id)
	{
		$projectsModel = $this->context->models->projects;
		$tasksModel = $this->context->models->tasks;
		$milestone = $projectsModel->getMilestone($id);
		$this->id = $milestone['project_id'];
		$this->milestone = $id;
		$this['milestoneForm']->setDefaults($milestone);
	}

	protected function createComponentMilestoneForm($name)
	{
		$form = new \Nette\Application\UI\Form($this, $name);
		$form->addHidden('id');
		$form->addHidden('project_id');
		if ($this->id !== null)
		{
			$form['project_id']->setValue($this->id);
		} else
		{
			$this->id = $form['project_id']->getValue();
		}
		if ($this->milestone !== null)
		{
			$form['id']->setValue($this->milestone);
		} else
		{
			$this->milestone = $form['id']->getValue();
		}
		$form->addText('name', 'Název:')->setRequired('Název milníku je povinný');
		$form->addDatePicker('start', 'Začátek:');
		$form->addDatePicker('deadline', 'Deadline:');
		$tasksModel = $this->context->models->tasks;
		$tasksContainer = new Nette\Forms\Container($form, 'tasks');

		if ($this->milestone != null)
		{

			$tasks = $tasksModel->getTasks(false, array('milestone_id' => $this->milestone));
			foreach ($tasks as $task)
			{
				$form['tasks']->addCheckbox($task['id'], $task['name'])->setDefaultValue(TRUE);
			}
			$tasks = $tasksModel->getTasks(false, array('project_id' => $this->id, 'milestone_id' => NULL));
			foreach ($tasks as $task)
			{
				$form['tasks']->addCheckbox($task['id'], $task['name']);
			}
		} elseif ($this->id != null)
		{
			$tasks = $tasksModel->getTasks(false, array('project_id' => $this->id, 'milestone_id' => NULL));
			foreach ($tasks as $task)
			{
				$form['tasks']->addCheckbox($task['id'], $task['name']);
			}
		} else
		{
			throw new Exception('Project ID or Milestone ID must be specified');
		}

		$form->addSubmit('save', 'Uložit');
		$form->onSuccess[] = callback($this, 'milestoneFormSubmitted');
		return $form;
	}

	public function milestoneFormSubmitted($form)
	{
		$values = $form->getValues();
		$projectsModel = $this->context->models->projects;
		if ($values['id'] != '') // edit
		{
			if ($projectsModel->editMilestone($values) !== false)
			{
				$this->flashMessage('Milník byl úspěšně upraven.');
				$this->redirect('Project:milestones', $values['project_id']);
			} else
			{
				$this->flashMessage('Chyba při úpravě milníku.', 'error');
			}
		} else
		{ // new
			if ($projectsModel->addMilestone($values) !== null)
			{
				$this->flashMessage('Milník byl úspěšně vytvořen.');
				$this->redirect('Project:milestones', $values['project_id']);
			} else
			{
				$this->flashMessage('Chyba při vytváření milníku.', 'error');
			}
		}
	}

	public function renderAddFile($id)
	{
		$this->id = $id;
	}

	protected function createComponentFileForm($name)
	{
		$form = new \Nette\Application\UI\Form($this, $name);
		$filesModel = $this->context->models->files;
		$types = $filesModel->getFileTypes()->fetchPairs('id', 'name');
		$form->addText('name', 'Název:');
		$form->addSelect('file_type_id', 'Typ:', $types);
		$form->addUpload('file', 'Soubor:');
		$form->addTextArea('description', 'Popis:');
		$form->addSubmit('save', 'Vložit');
		$form->addHidden('project_id', $this->id);
		if($this->id === null){
			$this->id = $form['project_id']->getValue();
		}
		$form->addHidden('user_id', $this->user->id);
		$form->onSuccess[] = callback($this, 'fileFormSubmitted');
		return $form;
	}

	public function fileFormSubmitted($form)
	{
		$values = $form->getValues();
		$file = $values->file;
		if ($file->isOk())
		{
			$path = $this->context->params['uploadDir'] . '/project/' . $this->id . '/' . $file->getSanitizedName();
			$file->move($path);
			unset($values['file']);
			$values['path'] = $path;
			if ($this->context->models->files->addProjectFile($values) !== null)
			{
				$this->flashMessage('Soubor byl úspěšně nahrán');
				$this->redirect('Project:documents',$this->id);
			} else
			{
				$this->flashMessage('Chyba při vkládání souboru.', 'error');
			}
		} else
		{
			$this->flashMessage('Chyba při nahrávání souboru.', 'error');
		}
	}

	public function actionDownloadFile($id)
	{
		$filesModel = $this->context->models->files;
		$file = $filesModel->getProjectFile($id);
		$response = new \Nette\Application\Responses\FileResponse($file['path']);
		$this->sendResponse($response);
	}
	
	/** @secured */
	public function handleDeleteFile($file)
	{
		if($this->context->models->files->deleteProjectFile($file)){
			$this->flashMessage('Soubor byl smazán');
		}  else
		{
			$this->flashMessage('Nastala chyba při mazání souboru','error');
		}
		$this->redirect('this');
	}

}
